package service

import (
	"context"
	"fmt"
	"gitee.com/cristiane/micro-mall-search/model/elasticsearch"
	"gitee.com/cristiane/micro-mall-search/pkg/code"
	"gitee.com/cristiane/micro-mall-search/proto/micro_mall_search_proto/search_business"
	"gitee.com/cristiane/micro-mall-search/repository"
	"strconv"
)

func SkuInventorySearch(ctx context.Context, req *search_business.SkuInventorySearchRequest) (result []*search_business.SkuInventoryEntry, retCode int) {
	result = make([]*search_business.SkuInventoryEntry, 0)
	retCode = code.Success
	rsp, searchCode := repository.Search(ctx, elasticsearch.ESIndexSkuInventory, "title", req.SkuKey)
	if searchCode != code.Success {
		retCode = code.ErrorServer
		return
	}
	result = make([]*search_business.SkuInventoryEntry, rsp.Total.Value)
	for i := 0; i < rsp.Total.Value; i++ {
		shopId, _ := rsp.Hits[i].Source["shop_id"].(int64)
		skuName, _ := rsp.Hits[i].Source["name"].(string)
		entry := &search_business.SkuInventoryEntry{
			SkuCode: rsp.Hits[i].ID,
			ShopId:  strconv.FormatInt(shopId, 10),
			SkuName: skuName,
			Score:   rsp.Hits[i].Score,
		}
		result[i] = entry
	}

	return result, retCode
}

func ShopSearch(ctx context.Context, req *search_business.ShopSearchRequest) (result []*search_business.ShopSearchEntry, retCode int) {
	result = make([]*search_business.ShopSearchEntry, 0)
	retCode = code.Success
	rsp, searchCode := repository.Search(ctx, elasticsearch.ESIndexShop, "nick_name", req.ShopKey)
	if searchCode != code.Success {
		retCode = code.ErrorServer
		return
	}
	fmt.Println("rsp.Total.Value==", rsp.Total.Value)
	result = make([]*search_business.ShopSearchEntry, rsp.Total.Value)
	for i := 0; i < rsp.Total.Value; i++ {
		shopName, _ := rsp.Hits[i].Source["nick_name"].(string)
		entry := &search_business.ShopSearchEntry{
			ShopId:   rsp.Hits[i].ID,
			ShopName: shopName,
			Score:    rsp.Hits[i].Score,
		}
		result[i] = entry
	}

	return result, retCode
}
